import React, { lazy, Suspense, useEffect, useRef } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { NavigationLayout } from '../../components/layout';
import { DashboardContent } from '../../components/dashboard';
import { ProfileContent } from '../../components/profile';
import { useAuthStore } from '../../stores/authStore';
import LazyLoadingFallback from '../../components/common/LazyLoadingFallback';

// 懒加载组件
const AdminPage = lazy(() => import('../../pages/admin/index.tsx'));
const NotificationDemo = lazy(() => import('../../components/common/NotificationDemo'));
const UIDemo = lazy(() => import('../../components/ui/UIDemo'));
const MagicBentoDemo = lazy(() => import('../../components/ui/MagicBentoDemo'));
const ThemeTest = lazy(() => import('../../components/common/ThemeTest'));
const HotDataPage = lazy(() => import('../../components/hot/HotDataPage'));
const ChatPage = lazy(() => import('../../pages/ai/ChatPage'));

// 爬虫子页面
const CrawlerTasksPage = lazy(() => import('../../pages/crawler/tasks'));
const CrawlerSchedulerPage = lazy(() => import('../../pages/crawler/scheduler'));
const CrawlerDataPage = lazy(() => import('../../pages/crawler/data'));
const CrawlerConfigPage = lazy(() => import('../../pages/crawler/config'));
const CrawlerMonitorPage = lazy(() => import('../../pages/crawler/monitor'));
const CrawlerLogsPage = lazy(() => import('../../pages/crawler/logs'));
const CrawlerPage = lazy(() => import('../../pages/crawler'));
const CrawlerOverviewPage = lazy(() => import('../../pages/crawler/overview'));

const NavigationPage: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { isAuthenticated, isLoading } = useAuthStore();
  const redirecting = useRef(false);
  const hasCheckedAuth = useRef(false);
  
  // 确保只有认证用户才能访问导航页面
  useEffect(() => {
    // 避免重复重定向
    if (!hasCheckedAuth.current && !isLoading) {
      hasCheckedAuth.current = true;
      if (!isAuthenticated) {
        console.log('未认证用户尝试访问导航页面，重定向到登录页');
        redirecting.current = true;
        navigate('/login', { replace: true });
      }
    }
  }, [isLoading, navigate, isAuthenticated]); // 添加isAuthenticated依赖

  // 根据路径决定渲染哪个内容组件
  const renderContent = () => {
    // 如果用户未认证且不在加载状态，不渲染内容
    if (!isLoading && !isAuthenticated) {
      return null;
    }
    
    switch (location.pathname) {
      case '/ai/chat':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <ChatPage />
          </Suspense>
        );
      case '/hot':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <HotDataPage />
          </Suspense>
        );
      case '/crawler/overview':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <CrawlerOverviewPage />
          </Suspense>
        );
      case '/crawler/tasks':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <CrawlerTasksPage />
          </Suspense>
        );
      case '/crawler/scheduler':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <CrawlerSchedulerPage />
          </Suspense>
        );
      case '/crawler/data':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <CrawlerDataPage />
          </Suspense>
        );
      case '/crawler/config':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <CrawlerConfigPage />
          </Suspense>
        );
      case '/crawler/monitor':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <CrawlerMonitorPage />
          </Suspense>
        );
      case '/crawler/logs':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <CrawlerLogsPage />
          </Suspense>
        );
      case '/notifications':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <NotificationDemo />
          </Suspense>
        );
      case '/ui-components':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <UIDemo />
          </Suspense>
        );
      case '/magic-bento':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <MagicBentoDemo />
          </Suspense>
        );
      case '/theme-test':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <ThemeTest />
          </Suspense>
        );
      case '/crawler':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <CrawlerPage />
          </Suspense>
        );
      case '/scheduler':
        return (
          <div style={{ padding: '24px', textAlign: 'center', color: '#fff' }}>
            <h2 style={{ color: '#61dca3' }}>⏰ 定时任务管理</h2>
            <p>可视化任务配置，支持Cron表达式</p>
          </div>
        );
      case '/analytics':
        return (
          <div style={{ padding: '24px', textAlign: 'center', color: '#fff' }}>
            <h2 style={{ color: '#61dca3' }}>📊 数据可视化</h2>
            <p>实时数据监控，丰富的图表展示</p>
          </div>
        );
      case '/users':
        return (
          <div style={{ padding: '24px', textAlign: 'center', color: '#fff' }}>
            <h2 style={{ color: '#61dca3' }}>👥 用户权限管理</h2>
            <p>基于RBAC的权限控制系统</p>
          </div>
        );
      case '/files':
        return (
          <div style={{ padding: '24px', textAlign: 'center', color: '#fff' }}>
            <h2 style={{ color: '#61dca3' }}>📁 文件管理</h2>
            <p>支持大文件上传、断点续传</p>
          </div>
        );
      case '/search':
        return (
          <div style={{ padding: '24px', textAlign: 'center', color: '#fff' }}>
            <h2 style={{ color: '#61dca3' }}>🔍 全文检索</h2>
            <p>基于Elasticsearch的搜索功能</p>
          </div>
        );
      case '/admin':
      case '/admin/dashboard':
      case '/admin/users':
      case '/admin/roles':
      case '/admin/permissions':
      case '/admin/crawlers':
      case '/admin/system':
        return (
          <Suspense fallback={<LazyLoadingFallback />}>
            <AdminPage />
          </Suspense>
        );
      case '/profile':
        return <ProfileContent />;
      case '/dashboard':
      default:
        return <DashboardContent />;
    }
  };

  const content = renderContent();
  return (
    <NavigationLayout>
      {content}
    </NavigationLayout>
  );
};

export default NavigationPage;